import { Component, ChangeDetectorRef, EventEmitter, Output } from "@angular/core";
import { NavController} from "ionic-angular";
import { UserDto } from "../../../shared/models/dto/user.dto";
import { StorageDto } from "../../../shared/models/dto/storage.dto";
import { CurdService } from "../../../shared/models/services/curd.service";
import { AsyncPipe } from '@angular/common';
import { SyncService } from '../../../shared/services/offline/sync.servie';
import { InspectionSyncService } from '../../../shared/services/offline/inspection-sync.servie';
import {NetStatus, SyncPushService} from "../../../shared/services/offline/sync-push.service";
import { SecureStorageService } from '../../../shared/services/secure-storage.services';
import {WorkOrderStatus, WorkOrderType} from "../../../shared/models/transform/work-order";
import {WorkOrderDto} from "../../../shared/models/dto/work-orders.dto";
import { InspectionTasksDto } from '../../../shared/models/dto/inspection/inspection-tasks.dto';
import { UtilsService } from "../../../shared/services/utils.services";
import {RoleStatus} from "../../../shared/models/role.status";
import { InspectionTasks } from "../../../shared/models/transform/inspection/inspection-tasks";
import { HttpService } from 'http-service';
import { API } from "../../../shared/models/api-path-extension";
import { CardService } from '../../../modules/card/services/card.service';
import { ActionSheetController } from 'ionic-angular';
import * as _ from 'lodash';
import { Network } from "@ionic-native/network";
import { Device } from "@ionic-native/device";
import { TimeDownCutPipe } from '../../../shared/components/charge-flow-path/charge-flow-path.component';

declare var window: {
  localStorage: {
    getItem: any,
  }
};

@Component({
    selector: 'comp-home-cards',
    templateUrl: './home-cards.component.html'
})
export class HomeCardsComponent {
  @Output() statisticsNum = new EventEmitter<object>();
  myInput: string;
  shouldShowCancel: string;
  hiddenSearch: boolean;
  updateTime: number = new Date().getTime();
  allUnpayment: any = 0.00;
  allUser: Array<{totalUnPaidAmount: any}>;
  customStorage: any;
  arrearsNum: number = 0;
  inspectionTaskNum: number;
  resumptionNumber: number = 0;
  role: string;
  countdown: any;
  overTime: boolean = false;
  marketing: RegExp;
  producer: RegExp;
  isGoto: boolean = true;
  userInfo: any;
  api: API;
  private _userCardList: any = [];
  set userCardList(userCardList) {
    this._userCardList = userCardList;
    this.updateCardDesc();
  }
  get userCardList() {
    return this._userCardList;
  }
  constructor(
      public curdService: CurdService,
      public navCtrl: NavController,
      private syncService: SyncService,
      private syncPushService: SyncPushService,
      private inspectionSyncService: InspectionSyncService,
      private utilsService: UtilsService,
      private ref: ChangeDetectorRef,
      private storage: SecureStorageService,
      public httpService: HttpService,
      private cardService: CardService,
      private network: Network,
      private device: Device,
      private actionSheetCtrl: ActionSheetController,
  ) {
    this.api = new API();
    this.role =  window.localStorage.getItem('role');
    this.marketing = new RegExp(RoleStatus.marketing);
    this.producer = new RegExp(RoleStatus.producer);
    if (this.role) {
      if (new RegExp(this.network.type).test(NetStatus.work) || !this.device.cordova) {
        this.isGoto = false;
        if (this.marketing.test(this.role)) {
          this.syncService.startFetch().subscribe(() => {
            // increasemental pulling data successfully
            console.log("increasemental pulling data success");
            this.getUpdateTime();
            this.getAllUser();
            this.utilsService.hiddenLoading();
            this.isGoto = true;
          }, (error: object) => {
            this.utilsService.hiddenLoading();
            console.error("increasemental pulling data failed" + error);
          });
        }
        if (this.producer.test(this.role)) {
          this.inspectionSyncService.startFetch().subscribe(() => {
            console.log("increasemental pulling data successfully");
            this.getUpdateTime();
            this.getInspectionTask();
            this.utilsService.hiddenLoading();
            this.isGoto = true;
          }, (error: object) => {
            console.log("increasemental pulling data failed" + error);
            this.utilsService.hiddenLoading();
            this.utilsService.tip("运检数据获取失败");
          });
        }
        this.userInfo = storage.get('userInfo').subscribe((res) => {
          if (res) {
            this.userInfo = res['data'];
          } else {
            this.httpService.get(this.api.path({ path: "userInfo" }).baseURL, null).subscribe((response) => {
              this.storage.set('userInfo', response);
              this.userInfo = response["data"];
            });
          }
        });
      }
      this.loadCard();
      this.cardService.cardAddOrDelStatus$.subscribe((card) => {
        this.userCardList = this.userCardList.map((c) => c.id === card['id'] ? card : c);
        this.storage.set('home_card_user_list', JSON.stringify(this.userCardList));
      });
      this.cardService.cardReorderStatus$.subscribe((cards) => {
        this.userCardList = cards;
        this.storage.set('home_card_user_list', JSON.stringify(this.userCardList));
      });
    }
  }

  loadCard(refresh = false) {
    if (refresh) {
      this.storage.remove('home_card_user_list');
    }
    this.storage.get('home_card_user_list').subscribe((userCardList) => {
      if (userCardList && !refresh) {
        this.userCardList = JSON.parse(userCardList);
      } else {
        if (new RegExp(this.network.type).test(NetStatus.work) || !this.device.cordova) {
          this.utilsService.showLoading();
          this.httpService.get(this.api.path({path: "cardListByUser"}).baseURL, null).subscribe((resp) => {
            this.userCardList = resp['data'];
            this.userCardList.sort((ca, cb) => ca.sequence < cb.sequence ? -1 : 1);
            this.storage.set('home_card_user_list', JSON.stringify(this.userCardList));
            this.utilsService.hiddenLoading();
          }, (err) => this.utilsService.hiddenLoading());
        }
      }
    });
  }

  ionViewDidEnter() {
    // this.loadCard();

    if (!this.isGoto) {
      return;
    }
    // this.role =  window.localStorage.getItem('role');
    this.getUpdateTime();
    if (this.marketing.test(this.role)) {
      this.getAllUser();
    }
    if (this.producer.test(this.role)) {
      this.getInspectionTask();
    }
  }


  update() {
    this.ionViewDidEnter();
  }

  goChargeList(str) {
    this.navCtrl.push("ChargeListPage", {status: str});
  }

  goInspectionList() {
    this.navCtrl.push("InspectionListPage");
  }

  search() {
    this.navCtrl.push("GlobalSearchPage");
  }

  goWorkTrack() {
    this.navCtrl.push("WorkTrackPage");
  }

  getUpdateTime() {
    this.curdService.simpleFetch(StorageDto)
      .then( (res) => {
        this.customStorage = Array.from(res["results"]);
        if (this.customStorage && this.customStorage.length > 0) {
          this.customStorage.forEach( (item, index) => {
            let value = item["value"];
            if (item["key"] === "lastFetchingDate" && value && value !== "null" ) {
              this.updateTime = value;
            }
          });
        }
        this.updateCardDesc();
      });
  }

  updateCardDesc() {
    this.userCardList.map((card) => {
      card.updatedTime = this.updateTime;
      card.clickEvent = () => null;
      switch (card.name) {
        case '催费':
        card.desc = `您有<span class="active">${ this.arrearsNum }</span>催费名单，欠 <span class="active">${ this.allUnpayment }</span>`;
        card.clickEvent = (_card) => this.goChargeList('charge');
        break;
        case '抄表':
        card.desc = `您有<span>0</span>条抄表信息`;
        card.waitdev = true;
        break;
        case '复电':
        card.desc = `您有<span class="active">${this.resumptionNumber ? this.resumptionNumber : 0}</span>` +
          `复电名单，剩余<span class="active">` + (this.overTime ? `<span class="active">-</span>` : '') +
          `${ new TimeDownCutPipe().transform(new AsyncPipe(this.ref).transform(this.countdown)) }</span>`;
        card.clickEvent = (_card) => this.goChargeList('resumption');
        break;
        case '抢修':
        card.desc = '您有<span>0</span>条抢修信息';
        card.waitdev = true;
        break;
        case '巡视':
        card.desc = '您有<span>0</span>条巡视信息';
        card.waitdev = true;
        break;
        case '检修':
        card.desc = `您有<span class="active">${this.inspectionTaskNum || 0}</span>个待检修任务`;
        card.clickEvent = (_card) => this.goInspectionList();
        break;
      }
    });
  }

  statisticsChanged() {
    this.statisticsNum.emit({
      arrearsNum: this.arrearsNum,
      resumptionNumber: this.resumptionNumber,
      inspectionTaskNum: this.inspectionTaskNum
    });
  }

  getAllUser() {
    this.curdService.simpleFetch(UserDto, ["id", "totalUnPaidAmount"])
      .then( (res) => {
        this.allUser = Array.from(res["results"]);
        this.arrearsNum = 0;
        this.allUnpayment = 0;
        let userId = [];
        this.allUser.forEach( (item, index) => {
          if (!item.totalUnPaidAmount) {
            item.totalUnPaidAmount = 0;
            userId.push(item["id"]);
          } else {
            if (item.totalUnPaidAmount > 0) {
              this.arrearsNum ++;
            }
          }
          this.allUnpayment += item.totalUnPaidAmount;
        });
        this.allUnpayment = this.allUnpayment.toFixed(2);
        this.updateCardDesc();
        this.statisticsChanged();
        if (userId.length > 0) {
          this.curdService.fetchByCondition(WorkOrderDto, {
            in: {
              userId: userId,
              workOrderStatus: [WorkOrderStatus.TO_BE_SUBMIT, WorkOrderStatus.APPROVED, WorkOrderStatus.TO_BE_APPROVED, WorkOrderStatus.REJECTED]
            },
            and: {
              type: WorkOrderType.POWERRECOVERY
            }
          }, ["payDate"])
            .then((results) => {
              let resumptionData = Array.from(results["results"]);
              if (resumptionData.length > 0) {
                this.resumptionNumber = resumptionData.length;
                let counter = this.utilsService.getCounter(resumptionData[0]["payDate"]);
                this.overTime = counter.isOverTime;
                this.countdown = this.utilsService.productionCountdown(counter.counter);
              } else {
                this.resumptionNumber = 0;
                this.countdown = this.utilsService.productionCountdown();
              }
              this.updateCardDesc();
              this.statisticsChanged();
              setTimeout(() => {
                this.ref.detectChanges();
              }, 500);
            });
        }
        this.ref.detectChanges();
      });
  }

  showCardActions(card) {
    const cardName = card.name;
    const actionSheet = this.actionSheetCtrl.create({
      title: '操作卡片 - ' + cardName,
      buttons: [ {
        text: '移除卡片',
        handler: () => {
          card.isAvailable = !card.isAvailable ? 1 : 0;
          const _tmpCardList = this.userCardList.map((c) => c.id === card.id ? {...c, isAvailable: 0} : c);
          this.storage.set('home_card_user_list', JSON.stringify(_tmpCardList));
          this.cardService.saveUserCards(this.userInfo.userId, _tmpCardList).then((res) => {
            if (!card.cardUserId) {
              this.loadCard(true);
            }
          });
        }
      }]
    });
    actionSheet.present();
    event.stopPropagation();
  }

  getInspectionTask() {
    this.curdService.fetchByCondition(InspectionTasksDto).then((res) => {
      let resData: Array<InspectionTasks> = Array.from(res['results']);
      this.inspectionTaskNum = resData.length;
      if (resData && resData.length > 0 ) {
        resData.forEach((item) => {
          if (item.status === 3) {
            this.inspectionTaskNum = this.inspectionTaskNum - 1;
          } else {
            this.inspectionTaskNum = this.inspectionTaskNum;
          }
        });
      }
      this.updateCardDesc();
      this.statisticsChanged();
      this.ref.detectChanges();
    });
  }

  getWorkTrackNumber() {
    let mun = 0;
    if (this.marketing.test(this.role)) {
      mun += this.arrearsNum;
      mun += this.resumptionNumber;
    }
    if (this.producer.test(this.role)) {
      mun += this.inspectionTaskNum;
    }
    return mun;
  }
    // chargeInfo(): CardComponentProperty {
    //     let prop = new CardComponentProperty("??", "??0?????");
    //     prop.footer = "???? " + new Date().toLocaleDateString();
    //     return prop;
    // }

}
